<template>
    <div class="profile-info">
      <div class="page-header">
        <div class="header-left">
          <h2>个人信息</h2>
          <p>查看和管理您的个人账户信息</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="editMode = true" v-if="!editMode">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
          <template v-else>
            <el-button @click="cancelEdit">取消</el-button>
            <el-button type="primary" @click="saveProfile" :loading="saveLoading">
              保存
            </el-button>
          </template>
        </div>
      </div>
  
      <div class="profile-content">
        <el-row :gutter="24">
          <!-- 左侧：头像和基本信息 -->
          <el-col :span="8">
            <el-card class="avatar-card">
              <div class="avatar-section">
                <div class="avatar-wrapper">
                  <el-avatar :size="120" :src="userInfo.avatar" />
                  <div class="avatar-overlay" v-if="editMode">
                    <el-upload
                      class="avatar-uploader"
                      action="#"
                      :show-file-list="false"
                      :before-upload="beforeAvatarUpload"
                    >
                      <el-icon class="avatar-uploader-icon"><Camera /></el-icon>
                    </el-upload>
                  </div>
                </div>
                <h3>{{ userInfo.realName }}</h3>
                <p class="user-role">{{ userInfo.roleName }}</p>
                <p class="user-department">{{ userInfo.department }}</p>
              </div>
              
              <div class="user-stats">
                <div class="stat-item">
                  <div class="stat-number">{{ userInfo.loginCount }}</div>
                  <div class="stat-label">登录次数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ userInfo.lastLoginDays }}</div>
                  <div class="stat-label">最后登录</div>
                </div>
                <div class="stat-item">
                  <div class="stat-number">{{ userInfo.accountAge }}</div>
                  <div class="stat-label">账户年龄</div>
                </div>
              </div>
            </el-card>
          </el-col>
  
          <!-- 右侧：详细信息 -->
          <el-col :span="16">
            <el-card>
              <template #header>
                <span>基本信息</span>
              </template>
              
              <el-form
                ref="profileForm"
                :model="userInfo"
                :rules="rules"
                label-width="100px"
                :disabled="!editMode"
              >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="用户名" prop="username">
                      <el-input v-model="userInfo.username" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="真实姓名" prop="realName">
                      <el-input v-model="userInfo.realName" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="邮箱" prop="email">
                      <el-input v-model="userInfo.email" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号" prop="phone">
                      <el-input v-model="userInfo.phone" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="性别" prop="gender">
                      <el-radio-group v-model="userInfo.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="生日" prop="birthday">
                      <el-date-picker
                        v-model="userInfo.birthday"
                        type="date"
                        placeholder="选择生日"
                        style="width: 100%"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="角色" prop="roleId">
                      <el-select v-model="userInfo.roleId" style="width: 100%">
                        <el-option
                          v-for="role in roles"
                          :key="role.id"
                          :label="role.name"
                          :value="role.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="部门" prop="departmentId">
                      <el-select v-model="userInfo.departmentId" style="width: 100%">
                        <el-option
                          v-for="dept in departments"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="地址" prop="address">
                  <el-input
                    v-model="userInfo.address"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入详细地址"
                  />
                </el-form-item>
                
                <el-form-item label="个人简介" prop="bio">
                  <el-input
                    v-model="userInfo.bio"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入个人简介"
                  />
                </el-form-item>
              </el-form>
            </el-card>
  
            <!-- 账户安全 -->
            <el-card style="margin-top: 20px;">
              <template #header>
                <span>账户安全</span>
              </template>
              
              <div class="security-items">
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">登录密码</div>
                    <div class="security-desc">建议定期更换密码，确保账户安全</div>
                  </div>
                  <el-button type="primary" @click="showChangePassword = true">
                    修改密码
                  </el-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">手机绑定</div>
                    <div class="security-desc">已绑定手机：{{ maskPhone(userInfo.phone) }}</div>
                  </div>
                  <el-button @click="showChangePhone = true">更换手机</el-button>
                </div>
                
                <div class="security-item">
                  <div class="security-info">
                    <div class="security-title">邮箱绑定</div>
                    <div class="security-desc">已绑定邮箱：{{ maskEmail(userInfo.email) }}</div>
                  </div>
                  <el-button @click="showChangeEmail = true">更换邮箱</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
  
      <!-- 修改密码对话框 -->
      <el-dialog
        v-model="showChangePassword"
        title="修改密码"
        width="500px"
        @close="resetPasswordForm"
      >
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
              v-model="passwordForm.currentPassword"
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showChangePassword = false">取消</el-button>
            <el-button type="primary" @click="changePassword" :loading="passwordLoading">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { defineComponent, ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Edit, Camera } from '@element-plus/icons-vue'
  
  export default defineComponent({
    name: 'ProfileInfo',
    components: {
      Edit,
      Camera
    },
    setup() {
      const editMode = ref(false)
      const saveLoading = ref(false)
      const showChangePassword = ref(false)
      const showChangePhone = ref(false)
      const showChangeEmail = ref(false)
      const passwordLoading = ref(false)
      
      const profileForm = ref(null)
      const passwordFormRef = ref(null)
      
      // 用户信息
      const userInfo = reactive({
        username: 'admin',
        realName: '张三',
        email: 'zhangsan@example.com',
        phone: '13800138000',
        gender: 'male',
        birthday: '1990-01-01',
        roleId: 1,
        departmentId: 1,
        address: '北京市朝阳区某某街道123号',
        bio: '热爱工作，积极向上，专注于商品溯源管理系统的开发与维护。',
        avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
        roleName: '系统管理员',
        department: '技术部',
        loginCount: 156,
        lastLoginDays: 2,
        accountAge: 365
      })
      
      // 角色列表
      const roles = ref([
        { id: 1, name: '系统管理员' },
        { id: 2, name: '商品管理员' },
        { id: 3, name: '质量检测员' },
        { id: 4, name: '普通用户' }
      ])
      
      // 部门列表
      const departments = ref([
        { id: 1, name: '技术部' },
        { id: 2, name: '商品部' },
        { id: 3, name: '质量部' },
        { id: 4, name: '运营部' }
      ])
      
      // 表单验证规则
      const rules = {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
      
      // 密码表单
      const passwordForm = reactive({
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      
      // 密码验证规则
      const passwordRules = {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
      
      // 保存个人信息
      const saveProfile = async () => {
        try {
          await profileForm.value.validate()
          saveLoading.value = true
          
          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          ElMessage.success('个人信息保存成功')
          editMode.value = false
        } catch (error) {
          console.error('保存失败:', error)
          ElMessage.error('保存失败，请检查输入信息')
        } finally {
          saveLoading.value = false
        }
      }
      
      // 取消编辑
      const cancelEdit = () => {
        editMode.value = false
        // 重置表单数据
        Object.assign(userInfo, {
          realName: '张三',
          email: 'zhangsan@example.com',
          phone: '13800138000',
          gender: 'male',
          birthday: '1990-01-01',
          roleId: 1,
          departmentId: 1,
          address: '北京市朝阳区某某街道123号',
          bio: '热爱工作，积极向上，专注于商品溯源管理系统的开发与维护。'
        })
      }
      
      // 头像上传
      const beforeAvatarUpload = (file) => {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 2
  
        if (!isJPG) {
          ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
        }
        if (!isLt2M) {
          ElMessage.error('上传头像图片大小不能超过 2MB!')
        }
        
        if (isJPG && isLt2M) {
          // 模拟上传
          const reader = new FileReader()
          reader.onload = (e) => {
            userInfo.avatar = e.target.result
          }
          reader.readAsDataURL(file)
        }
        
        return false
      }
      
      // 修改密码
      const changePassword = async () => {
        try {
          await passwordFormRef.value.validate()
          passwordLoading.value = true
          
          // 模拟API请求
          await new Promise(resolve => setTimeout(resolve, 1000))
          
          ElMessage.success('密码修改成功')
          showChangePassword.value = false
          resetPasswordForm()
        } catch (error) {
          console.error('修改密码失败:', error)
          ElMessage.error('修改密码失败，请检查输入信息')
        } finally {
          passwordLoading.value = false
        }
      }
      
      // 重置密码表单
      const resetPasswordForm = () => {
        if (passwordFormRef.value) {
          passwordFormRef.value.resetFields()
        }
        Object.assign(passwordForm, {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        })
      }
      
      // 掩码手机号
      const maskPhone = (phone) => {
        if (!phone) return ''
        return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
      }
      
      // 掩码邮箱
      const maskEmail = (email) => {
        if (!email) return ''
        const [username, domain] = email.split('@')
        return `${username.substring(0, 2)}***@${domain}`
      }
      
      onMounted(() => {
        // 加载用户信息
      })
      
      return {
        editMode,
        saveLoading,
        showChangePassword,
        showChangePhone,
        showChangeEmail,
        passwordLoading,
        profileForm,
        passwordFormRef,
        passwordForm,
        userInfo,
        roles,
        departments,
        rules,
        passwordRules,
        saveProfile,
        cancelEdit,
        beforeAvatarUpload,
        changePassword,
        resetPasswordForm,
        maskPhone,
        maskEmail
      }
    }
  })
  </script>
  
  <style scoped>
  .profile-info {
    padding: 20px;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  
  .header-left h2 {
    margin: 0 0 5px 0;
    color: #2563eb;
  }
  
  .header-left p {
    margin: 0;
    color: #666;
    font-size: 14px;
  }
  
  .profile-content {
    .avatar-card {
      .avatar-section {
        text-align: center;
        padding: 20px 0;
        
        .avatar-wrapper {
          position: relative;
          display: inline-block;
          margin-bottom: 16px;
          
          .avatar-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s;
            cursor: pointer;
            
            &:hover {
              opacity: 1;
            }
            
            .avatar-uploader-icon {
              font-size: 24px;
              color: white;
            }
          }
        }
        
        h3 {
          margin: 0 0 8px 0;
          color: #2563eb;
        }
        
        .user-role {
          margin: 0 0 4px 0;
          color: #666;
          font-size: 14px;
        }
        
        .user-department {
          margin: 0;
          color: #999;
          font-size: 12px;
        }
      }
      
      .user-stats {
        display: flex;
        justify-content: space-around;
        padding: 20px 0;
        border-top: 1px solid #f0f0f0;
        
        .stat-item {
          text-align: center;
          
          .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #2563eb;
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
  
  .security-items {
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .security-info {
        .security-title {
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }
        
        .security-desc {
          font-size: 12px;
          color: #666;
        }
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  
  @media (max-width: 768px) {
    .page-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .header-right {
      width: 100%;
      display: flex;
      gap: 10px;
    }
    
    .profile-content {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }
  </style> 